<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span
          class="arrow"
          @click="$router.back()"
        ><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id? '编辑企业':'添加企业' }}</span>
      </div>
      <div class="right">黑马程序员</div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form
            ref="ruleForm"
            :model="addForm"
            :rules="addRules"
            label-width="100px"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- list-type="picture"
                :file-list="fileList" -->
              <el-upload
                class="upload-demo"
                action="#"
                :http-request="upload"
                :before-remove="remove"
                :before-upload="beforeUpload"
                :on-change="handleChange"
                list-type="picture"
                :file-list="fileList"
              >
                <!-- 上传成功之后  按钮应该禁用 -->
                <el-button :disabled="addForm.businessLicenseId !== ''" size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500KB</div>
              </el-upload>
              <!-- <img v-show="addForm.businessLicenseUrl" :src="addForm.businessLicenseUrl" alt="" class="img"> -->
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
// 渲染行业select
import { getIndustryListAPI, createEnterpriseAPI, getEnterpriseDetailAPI, updateEnterpriseAPI } from '@/api/enterprise'
import { uploadAPI } from '@/api/common'
export default {
  data() {
    const validatePhone = (rule, value, cb) => {
      if (/^1[3-9]\d{9}$/.test(value)) {
        cb()
      } else {
        cb(new Error('请输入正确手机号'))
      }
    }
    return {
      fileList: [],
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      addRules: {
        name: [{ required: true, message: '企业名称为必填', trigger: 'blur' }],
        legalPerson: [
          { required: true, message: '法人为必填', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址为必填', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业为必填', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人为必填', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ]
      },
      industryList: []
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    // 获取行业列表
    this.getIndustryList()
    // 编辑的时候调用详情接口
    if (this.id) {
      this.getEnterpriseDetail()
    }
  },
  methods: {
    async getIndustryList() {
      const res = await getIndustryListAPI()
      this.industryList = res.data
    },
    // 上传函数
    async upload(data) {
      // data.file 就是要上传的文件
      console.log(data)
      // 测试
      // 上传功能
      // 1. 准备formdata数据
      // 2. 掉接口传入formdata数据即可
      const fd = new FormData() // formData实例对象 append方法是加值的
      fd.append('file', data.file)
      fd.append('type', 'businessLicense')
      const res = await uploadAPI(fd)
      console.log(res)
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url
      // this.fileList = [{
      //   status: 'success',
      //   name: '营业执照',
      //   url: res.data.url
      // }]
      // 单独校验表单，清除错误信息
      this.$refs.getEnterpriseDetail.validateField('businessLicenseId')
    },
    handleChange(file, fileList) {
      console.log(file, fileList)
      this.fileList = [{
        status: 'success',
        name: '营业执照',
        url: URL.createObjectURL(file.raw)
      }]
    },
    remove() {
      this.addForm.businessLicenseId = ''
      this.addForm.businessLicenseUrl = ''
      // this.fileList = []
    },
    // 上传之前做的事
    beforeUpload(file) {
      // 允许的类型
      const type = file.type === 'image/png'
      // B 转成 KB
      // 允许的大小
      const lt5M = file.size / 1024 < 500
      if (!type) {
        this.$message.error('上传的格式不对')
        return false
      }
      if (!lt5M) {
        this.$message.error('上传的文件太大了')
      }
      // 返回值如果为false 就不上传了
      return type && lt5M
    },
    // 点击确定提交表单
    confirm() {
      this.$refs.ruleForm.validate(async valid => {
        console.log(valid)
        if (valid) {
          if (this.id) {
            const form = {
              ...this.addForm,
              id: this.id
            }
            await updateEnterpriseAPI(form)
          } else {
            await createEnterpriseAPI(this.addForm)
          }

          this.$message.success(this.id ? '编辑成功' : '添加成功')
          this.$router.back()
        }
      })
    },
    // 获取详情接口
    async getEnterpriseDetail() {
      const res = await getEnterpriseDetailAPI(this.id)
      console.log(res)
      const {
        name,
        legalPerson,
        registeredAddress, // 注册地址
        industryCode, // 所在行业
        contact, // 企业联系人
        contactNumber, // 联系人电话
        businessLicenseUrl, // 营业执照url
        businessLicenseId // 营业执照id
      } = res.data
      this.addForm = {
        name,
        legalPerson,
        registeredAddress, // 注册地址
        industryCode, // 所在行业
        contact, // 企业联系人
        contactNumber, // 联系人电话
        businessLicenseUrl, // 营业执照url
        businessLicenseId // 营业执照id
      }
      // 还原上传图片列表
      this.fileList.push({
        status: 'success',
        name: '营业执照',
        url: businessLicenseUrl
      })
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
  .img{
    width: 150px;
    height: 150px;
    border-radius: 4px;
  }
}
</style>
